package com.frontier.gateway8000.filter;

import com.frontier.exception.CustomException;
import com.frontier.gateway8000.enumeration.ExceptionEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 自定义拦截器
 *
 * @author YLS-XuXu
 * @time 2022/2/24
 */
@Component
@Slf4j
public class SxdGatewayFilterFactory extends AbstractGatewayFilterFactory<SxdGatewayFilterFactory.SxdConfig> {
    public SxdGatewayFilterFactory() {
        //固定写法
        super(SxdGatewayFilterFactory.SxdConfig.class);
        log.info("Loaded GatewayFilterFactory [Authorize]");
    }

    /**
     * 自定义拦截器内部逻辑
     *
     * @param config
     * @return org.springframework.cloud.gateway.filter.GatewayFilter
     */
    @Override
    public GatewayFilter apply(SxdConfig config) {
        return (exchange, chain) -> {
            //判断是否开启自定义拦截器，未开启直接下一个链路
            if (!config.isEnabled()) {
                return chain.filter(exchange);
            }
            ServerHttpRequest request = exchange.getRequest();
            HttpHeaders headers = request.getHeaders();
            //从请求头中获取token
            String token = headers.getFirst("token");
            //token为空，手动抛出
            if (StringUtils.isEmpty(token)) {
                throw new CustomException(ExceptionEnum.TOKEN_PARSING_ERROR);
            }
            //模拟token校验
            if (token.equals("1qazxsw23edcvfr45tgbnhy67ujm")) {
                log.info("校验通过");
            } else {
                throw new CustomException(ExceptionEnum.TOKEN_PARSING_ERROR);
            }
            return chain.filter(exchange);
        };
    }

    /**
     * 读取配置文件中的参数 赋值到 配置类中
     *
     * @return 配置1列表
     */
    @Override
    public List<String> shortcutFieldOrder() {
        //Config.enabled
        return Arrays.asList("enabled");
    }

    /**
     * 内部类，用于设置自定义拦截器需要的参数
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class SxdConfig {
        // 控制是否开启认证
        private boolean enabled;
    }

}
